﻿/***************
 * Copyright 2009 (C) 
 * Timur Fanshteyn
 * Blog: http://blog.tfanshteyn.com
 * ************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Collections;
using Tangosol.Util;

namespace Coherence.Linq
{
    public interface ICoherenceQueryable
    {
        IFilter Filter { get; }
    }

    public class CoherenceQuery<T> : ICoherenceQueryable, IQueryable<T>, IQueryable, IEnumerable<T>, IEnumerable
    {
        #region Constructors
        /// <summary>
        /// This constructor is called by the client to create the data source.
        /// </summary>
        public CoherenceQuery()
        {
            Construct(new CoherenceQueryProvider(), Expression.Constant(this));
        }

        public CoherenceQuery(IQueryProvider provider)
        {
            Construct(provider, Expression.Constant(this));
        }


        /// <summary>
        /// This constructor is called by Provider.CreateQuery().
        /// </summary>
        /// <param name="expression"></param>
        public CoherenceQuery(CoherenceQueryProvider provider, Expression expression)
        {
            Construct(provider, expression);
        }

        private void Construct(IQueryProvider provider, Expression expression)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            //TODO: SOMETHING
            //if (!typeof(IQueryable<TData>).IsAssignableFrom(expression.Type))
            //{
            //    throw new ArgumentOutOfRangeException("expression");
            //}

            Provider = provider;
            Expression = expression;
        }
        #endregion

        #region Properties

        public IQueryProvider Provider { get; private set; }
        public Expression Expression { get; private set; }
        public Type ElementType
        {
            get { return typeof(T); }
        }
        public IFilter Filter
        {
            get
            {
                var expression = Evaluator.PartialEval(Expression);
                return new CoherenceQueryTranslator().Translate(expression).Filter;
            }
        }
        #endregion

        #region Enumerators
        public IEnumerator<T> GetEnumerator()
        {
            IEnumerable t = (IEnumerable)this.Provider.Execute(this.Expression);
            return t.Cast<T>().GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return (Provider.Execute<System.Collections.IEnumerable>(Expression)).GetEnumerator();
        }
        #endregion
    }
}
